//
//  SendView.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/4/3.
//  Copyright © 2017年 刘晓晨. All rights reserved.
///Users/xiaoyu/Desktop/LiuWeiBo/LiuWeiBo/LiuWeiBo/Classes/View/SendView/SendView.swift:34:21: Invalid redeclaration of 'buttonArray'

import UIKit
import pop


class SendView: UIView {

    //懒加载模糊视图
    fileprivate lazy var backImageView:UIImageView = {
        let imageView = UIImageView()
        imageView.image = self.cutScreen().applyLightEffect()
        return imageView
    }()
    
    fileprivate lazy var tipImageView:UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
        return imageView
    }()
    
    fileprivate lazy var buttonArray:[SenderButton] = [SenderButton]()
    
    override init(frame: CGRect) {
        super.init(frame: (UIApplication.shared.keyWindow?.bounds)!)
        setupUI()
    }
    
    fileprivate lazy var buttonTypeArray:[LiuSendButtonModel] = {
        return self.loadPlist()
    }()
    
    fileprivate var targetVc:UIViewController?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI() {
        
        alpha = 0
        
        addSubview(backImageView)
        addSubview(tipImageView)
        
        backImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        tipImageView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(200)
        }
        
        //添加子按钮
        addChildButton()
        
    }
    
    fileprivate func addChildButton() {
        
        //按钮的大小
        let buttonWidth:CGFloat = 80
        let buttonHeight:CGFloat = 110
        
        //按钮的间距
        let buttonMargin = (screenWidth - 3 * buttonWidth) / 4
        
        //循环创建button
        for i in 0..<buttonTypeArray.count {
            
            let buttonCompose = buttonTypeArray[i]
            
            let button = SenderButton()
            button.setTitle(buttonCompose.title!, for: .normal)
            button.setImage(UIImage(named:buttonCompose.icon!), for: .normal)
            button.setTitleColor(UIColor.darkGray, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.tag = i
            
            //按钮添加点击事件
            button.addTarget(self, action: #selector(buttonAction(button:)), for: .touchUpInside)
            //计算行数
            let row = i / 3
            //计算列数
            let col = i % 3
            
            //设置button的frame
            button.x = CGFloat(col) * buttonWidth + CGFloat(col + 1) * buttonMargin
            
            button.y = CGFloat(row) * (buttonHeight + buttonMargin) + screenHeight
            
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
            //添加按钮
            addSubview(button)
            
            //添加到数组中
            buttonArray.append(button)
            
            
        }
        
        //开启动画
        buttonAnimation(isUp: true)
        
        
        
    }
    
    //动画
    fileprivate func buttonAnimation(isUp:Bool) {
        
        var currentalpha:CGFloat = 1
        
        if !isUp {
            buttonArray = buttonArray.reversed()
            currentalpha = 0
        }
        
        //遍历数组,添加动画
        for (index,button) in buttonArray.enumerated() {
//            UIView.animate(withDuration: 0.35, delay: Double(index) * 0.025, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
//                //修改按钮的y值
//                if isUp {
//                    button.y -= 300
//                } else {
//                    button.y += 300
//                }
//            }, completion: { (_) in
//            })
            
            //创建pop动画
            let popAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            //设置抖动幅度
            popAnimation?.springBounciness = 10
            
            //设置抖动速度
            popAnimation?.springSpeed = 10
            
            //设置动画时长
            popAnimation?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            
            //动画执行的目的地
            if isUp {
                popAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY - 320)
            } else {
                popAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY + 320)
            }
            
            //执行动画
            button.pop_add(popAnimation, forKey: nil)
        }
        
        UIView.animate(withDuration: 0.4) {
            self.alpha = currentalpha
        }
    }
    
    fileprivate func cutScreen() -> UIImage {
        
        let  window = UIApplication.shared.keyWindow!
        
        //开启图片上下文
        UIGraphicsBeginImageContext(CGSize(width: screenWidth, height: screenHeight))
        
        //将view渲染到上下文中
        window.drawHierarchy(in: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), afterScreenUpdates: false)
        
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
        
    }
    
    //点击viewde的时候从父试图移除
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
            self.buttonAnimation(isUp: false)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.5) {
            self.removeFromSuperview()
        }
  
        
    }
    
    //解析plist文件
    fileprivate func loadPlist() -> [LiuSendButtonModel] {
        
        //获取plist文件路径
        let plistPath = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        //获取数组
        let dicArray = NSArray.init(contentsOfFile: plistPath) as! [[String:Any]]
        
        return NSArray.yy_modelArray(with: LiuSendButtonModel.self, json: dicArray) as! [LiuSendButtonModel]
    }
    
    //按钮的点击
    @objc fileprivate func buttonAction(button:UIButton) {
        //按钮变大变小动画
        UIView.animate(withDuration: 0.25, animations: {
            for btn in self.buttonArray {
                btn.alpha = 0.5
                if btn == button {
                   btn.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
                } else {
                    btn.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
                }
            }
        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: { 
                //完成后还原
                for btn in self.buttonArray {
                    btn.alpha = 1
                    btn.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                //跳转控制器
                //获取类
                let vcClass = NSClassFromString(self.buttonTypeArray[button.tag].className!) as! UIViewController.Type
                
                //创建对象
                let vc = vcClass.init()
                
                //嵌套导航控制器
                let nav = LiuNavigationController(rootViewController: vc)
                
                //目标控制器跳转
                self.targetVc?.present(nav, animated: true, completion: { 
                    //跳转完成移除view
                    self.removeFromSuperview()
                })
            })
        }
        
    }
    
    //添加到tabbar上
    func show(viewController:UIViewController) {
        //将撰写页面添加到window上
        self.targetVc = viewController
        
        viewController.view.addSubview(self)
     
    }

}
